package com.cb.zuul.filter;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

public class AccessFilter extends ZuulFilter {
	private static Logger log = LoggerFactory.getLogger(ZuulFilter.class);
	
	//判断过滤器是否需要被执行，可以通过该函数来执行过滤器的有效范围
	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		log.info("send {} request to {}",request.getMethod(),request.getRequestURL().toString());
		Object accessToken = request.getParameter("accessToken");
		if(accessToken == null){
			log.warn("access token is empty");
			ctx.setSendZuulResponse(false);
			ctx.setResponseStatusCode(401);
			return null;
		}
		log.info("access token ok");
		return null;
	}

	//过滤器类型，决定过滤器在请求的哪个生命周期中执行
	@Override
	public String filterType() {
		return "pre";
	}

	//过滤器的执行顺序。当请求在一个阶段中存在多个过滤器时，需要根据该方法返回的值来依次执行
	@Override
	public int filterOrder() {
		return 0;
	}

}
